// 云函数入口文件
const cloud = require("wx-server-sdk");

cloud.init();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();

  cloud.updateConfig({
    env: wxContext.ENV == 'local' ? 'test-go5gy' : wxContext.ENV
  });

  const db = cloud.database();

  const { source_id, url } = event;
  console.log(source_id, url)

  // 获取源
  const source = await db
    .collection("book_sources")
    .doc(source_id)
    .field({ content: true })
    .get();

  // console.log(source, url)
  if (source.data && source.data.content) {
    const res = await cloud.callFunction({
      name: "worm",
      data: {
        url: url,
        type: source.data.content.type,
        result: source.data.content.result
      }
    });
    // console.log(res)
    if (!res.result) {
      return { errMsg: "请求错误" };
    }
    return { errMsg: "ok", data: res.result };
  } else {
    return {
      errMsg: source.errMsg,
      data
    };
  }
};
